package com.zhehekeji.opsys.api.service.manager;

import java.util.Date;

import org.apache.cxf.common.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zhehekeji.opsys.api.code.UserOrderResultCode;
import com.zhehekeji.opsys.api.common.util.ResultCode;
import com.zhehekeji.opsys.api.entity.TProduct;
import com.zhehekeji.opsys.api.entity.TUser;
import com.zhehekeji.opsys.api.entity.TUserOrder;
import com.zhehekeji.opsys.api.resp.CheckRegisterResp;
import com.zhehekeji.opsys.api.resp.UserOrderResp;
import com.zhehekeji.opsys.api.resp.UserRegisterResp;
import com.zhehekeji.opsys.api.resp.UserUpdateResp;
import com.zhehekeji.opsys.api.service.CommonService;
import com.zhehekeji.opsys.api.service.validate.CheckRegisterValidate;
import com.zhehekeji.opsys.api.service.validate.UserOrderValidate;
import com.zhehekeji.opsys.api.service.validate.UserRegisterValidate;
import com.zhehekeji.opsys.api.service.validate.UserUpdateValidate;
import com.zhehekeji.opsys.api.service.validate.ValidateRets;
import com.zhehekeji.opsys.api.service.validate.args.UserOrderValidateArgs;
import com.zhehekeji.opsys.api.service.validate.args.UserRegisterArgs;

/**
 * @ClassName UserManagerService
 * @Description TODO
 * @author chenweiliu chenwei.liu@163.com
 * @date 2015-4-14   上午10:37:26
 */
@Service
@Transactional
public class UserManagerService extends CommonService {
	
	private final static Logger logger = LoggerFactory.getLogger(UserManagerService.class);
	
	@Autowired
	private UserOrderValidate userOrderValidate;
	@Autowired
	private UserRegisterValidate userRegisterValidate;
	@Autowired
	private CheckRegisterValidate checkRegisterValidate;
	@Autowired
	private UserUpdateValidate userUpdateValidate;
	
	public UserOrderResp order(String productCode, Integer point, String userID, Long cpCode){
		UserOrderResp resp = new UserOrderResp();
		logger.info("新增订单productCode["+productCode+"],point["+point+"],userID["+userID+"],cpCode["+cpCode+"]");
		Date currentDate = new Date();
		try {
			/**
			  * 验证参数有效性
			  */
			 ValidateRets<Object[]> tmpTUserOrderValidateRets = userOrderValidate.validate(new UserOrderValidateArgs(resp, productCode, point, userID, cpCode));
			 
			 if (!tmpTUserOrderValidateRets.isSuccess()) return resp;
			 /**
			  * 更新用户积分
			  */
			 Object[] tmpObjectArray = tmpTUserOrderValidateRets.getEntity();
			 TUser tmpTUser = null;
			 TProduct tmpTProduct = null;
			 
			 for (Object tmpObject : tmpObjectArray){
				 if (tmpObject instanceof TUser){
					 tmpTUser = (TUser) tmpObject;
					 continue;
				 }
				 if (tmpObject instanceof TProduct){
					 tmpTProduct = (TProduct) tmpObject;
					 continue;
				 }
			 }
			 Integer tmpTotalPoint = tmpTUser.getTotalPoint();
			 tmpTotalPoint = tmpTotalPoint == null ? 0 : tmpTotalPoint;
			 tmpTotalPoint = tmpTotalPoint + point;
			 tmpTUser.setTotalPoint(tmpTotalPoint);
			 Integer tmpAvailablePoint = tmpTUser.getAvailablePoint();
			 tmpAvailablePoint = tmpAvailablePoint == null ? 0 : tmpAvailablePoint;
			 tmpAvailablePoint = tmpAvailablePoint + point;
			 tmpTUser.setAvailablePoint(tmpAvailablePoint);
			 entityDao.update(tmpTUser);
			
			 /**
			  * 新增订单
			  */
			 TUserOrder tmpTUserOrder = new TUserOrder();
			 tmpTUserOrder.setAccount(userID);
			 tmpTUserOrder.setCpCode(cpCode);
			 tmpTUserOrder.setCreateTime(currentDate);
			 tmpTUserOrder.setPoint(point);
			 tmpTUserOrder.setProductCode(productCode);
			 tmpTUserOrder.setProductName(tmpTProduct.getName());
			 entityDao.saveObj(tmpTUserOrder);
			 logger.info("新增订单成功");
		}catch (Exception e){
			logger.error("新增订购失败，程序异常，" + e.getMessage(), e);
			resp.setResultCode(UserOrderResultCode.APPLICATION_EXCEPTION);
			resp.setResultDesc("新增订购失败，程序异常！");
		}
		return resp;
	}
	
	public UserRegisterResp register(String userID, String userName, String mobileNo, Long cpCode) {
		UserRegisterResp resp = new UserRegisterResp();
		try {
			/**
			 * 验证参数
			 */
			ValidateRets<TUser> tmpTUserValidateRets = userRegisterValidate.validate(new UserRegisterArgs(resp, userID, mobileNo, cpCode));
			if (!tmpTUserValidateRets.isSuccess()) return  resp;
			/**
			 * 新增用户
			 */
			TUser tmpTUser = new TUser();
			tmpTUser.setAccount(userID);
			tmpTUser.setName(userName);
			tmpTUser.setAvailablePoint(0);
			tmpTUser.setCreateTime(new Date());
			tmpTUser.setCpCode(cpCode);
			tmpTUser.setMobile(mobileNo);
			tmpTUser.setStatus(1);
			tmpTUser.setTotalPoint(0);
			entityDao.saveObj(tmpTUser);
			 logger.info("账号注册成功");
		}catch (Exception e){
			logger.error("账号注册失败，程序异常，" + e.getMessage(), e);
			resp.setResultCode(ResultCode.APPLICATION_EXCEPTION);
			resp.setResultDesc("账号注册失败，程序异常！");
		}
		return resp;
	}
	
	public CheckRegisterResp checkRegister(String userID, Long cpCode) {
		CheckRegisterResp resp = new CheckRegisterResp();
		try {
			/**
			 * 验证参数
			 */
			ValidateRets<TUser> tmpTUserValidateRets = checkRegisterValidate.validate(new UserRegisterArgs(resp, userID, null, cpCode));
			if (tmpTUserValidateRets.isSuccess()) {
				logger.info("检查成功");
			}
		}catch (Exception e){
			logger.error("账号注册失败，程序异常，" + e.getMessage(), e);
			resp.setResultCode(ResultCode.APPLICATION_EXCEPTION);
			resp.setResultDesc("账号注册失败，程序异常！");
		}
		return resp;
	}

	public UserUpdateResp update(String userID, String userName, String mobileNo, Long cpCode) {
		
		UserUpdateResp resp = new UserUpdateResp();
		try {
			/**
			 * 验证参数
			 */
			ValidateRets<TUser> tmpTUserValidateRets = userUpdateValidate.validate(new UserRegisterArgs(resp, userID, mobileNo, cpCode));
			if (!tmpTUserValidateRets.isSuccess()) return  resp;
			/**
			 * 更新用户
			 */
			TUser tmpTUser = tmpTUserValidateRets.getEntity();
			boolean tmpUpdate = false;
			//boolean tmpUpdateMobile = false;
			if (!StringUtils.isEmpty(userName)){
				tmpTUser.setName(userName);
				tmpUpdate = true;
			}
			if (!StringUtils.isEmpty(mobileNo)){
				tmpTUser.setMobile(mobileNo);
				tmpUpdate = true;
				//tmpUpdateMobile = true;
			}
			if (tmpUpdate){
				entityDao.update(tmpTUser);
			}
			/*if (tmpUpdateMobile) {
				*//**
				 * 更新中奖结果
				 *//*
				List<TWinningResult> tmpListTWinningResult = entityDao.getScrollData(TWinningResult.class, "o.account=?1", new Object[]{userID});
				if (tmpListTWinningResult != null && !tmpListTWinningResult.isEmpty()){
					for (TWinningResult tmpTWinningResult : tmpListTWinningResult){
						tmpTWinningResult.setMobile(mobileNo);
						entityDao.update(tmpTWinningResult);
					}
				}
			}*/
			logger.info("账号更新成功");
		}catch (Exception e){
			logger.error("账号更新失败，程序异常，" + e.getMessage(), e);
			resp.setResultCode(ResultCode.APPLICATION_EXCEPTION);
			resp.setResultDesc("账号更新失败，程序异常！");
		}
		return resp;
		
	}
}
